<?php

namespace Seller\Controller;

class AccuntController extends BaseController {

    private $_orgin_sms_key = 'ORGIN_SMS_KEY_CEHCKED';
    private $_new_sms_key = 'NEW_SMS_KEY_CEHCKED';
    private $_app_key_show_key = 'APP_KEY_SHOW_KEY';

    public function info() {
        $this->display();
    }

    /**
     * 原始手机认证码
     */
    public function orginMobileCheck() {
        $rand_data = rand(100000, 999999);
        S($this->_orgin_sms_key, $rand_data, array('expire' => 3000));
        \Common\Api\SmsApi::init()->sendSms('您的验证码：' . $rand_data . '，切记打死都不能给别人说哦。', $this->__seller_info['contact_tel']);
        $this->ajaxReturn(array('status' => 1, 'msg' => '短信发送成功'));
    }

    /**
     * APP KEY验证码发送
     */
    public function appKeyCheck() {
        $rand_data = rand(100000, 999999);
        S($this->_app_key_show_key, $rand_data, array('expire' => 3000));
        \Common\Api\SmsApi::init()->sendSms('APP KEY查看验证码：' . $rand_data . '，切记打死都不能给别人说哦。', $this->__seller_info['contact_tel']);
        $this->ajaxReturn(array('status' => 1, 'msg' => '短信发送成功'));
    }

    /**
     * 新手机认证码
     */
    public function newMobileCheck() {
        isset($this->__get['mobile']) && $this->__get['mobile'] ? $mobile = $this->__get['mobile'] : $this->ajaxReturn(array('status' => 0, 'msg' => '手机号码不能为空'));
        $rand_data = rand(100000, 999999);
        S($this->_new_sms_key, $rand_data, array('expire' => 3000));
        \Common\Api\SmsApi::init()->sendSms('您的验证码：' . $rand_data . '，切记打死都不能给别人说哦。', $mobile);
        $this->ajaxReturn(array('status' => 1, 'msg' => '发送成功'));
    }

    /**
     * 手机号修改
     */
    public function mobileSave() {
        if (IS_POST) {
            if (!isset($this->__post['mobile']) || !preg_match('/^1[3-8]{1}[0-9]{9}$/i', $this->__post['mobile'])) {
                $this->error('手机号错误');
            }
            if (!isset($this->__post['orgin_code']) || $this->__post['orgin_code'] != S($this->_orgin_sms_key)) {
                $this->error('原始手机验证码错误');
            }
            if (!isset($this->__post['new_code']) || $this->__post['new_code'] != S($this->_new_sms_key)) {
                $this->error('新手机验证码错误');
            }
            S($this->_orgin_sms_key, null);
            S($this->_new_sms_key, null);
            if (M('customer')->save(array('id' => $this->__seller_info['id'], 'contact_tel' => $this->__post['mobile']))) {
                $_SESSION[$this->_soller_login_key] = M('customer')->find($this->__seller_info['id']);
                $this->success('手机号修改成功', U('Accunt/info'));
            }
            $this->error('手机号修改失败，请重新再试');
        } else {
            S($this->_orgin_sms_key, null);
            S($this->_new_sms_key, null);
            $this->display();
        }
    }

    /**
     * API安全
     */
    public function security() {
        $this->display();
    }

    /**
     * API安全KEY查看
     */
    public function appKeyShow() {
        if (IS_POST) {
            if (!isset($this->__post['code']) || $this->__post['code'] != S($this->_app_key_show_key)) {
                exit(json_encode(array('status' => 0, 'msg' => '验证失败，请核对验证码')));
            }
            S($this->_app_key_show_key, null);
            exit(json_encode(array('status' => 1, 'key' => $this->__seller_info['key'])));
        } else {
            S($this->_app_key_show_key, null);
            $this->display();
        }
    }

    /**
     * 平台对接
     */
    public function platformBind() {
        $model = M('customer_platform_bind');
        $where = array('customer_id' => $this->__seller_info['id']);
        if (isset($this->__get['name']) && $this->__get['name']) {
            $where['name'] = array('LIKE', '%' . $this->__get['name'] . '%');
        }
        $list = $model->where($where)->page($this->__page, $this->__row)->order('id DESC')->select();
        $total = $model->where($where)->count();
        $this->__assignPage($total);
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            }
        }
        $this->assign('lists', $list);
        $this->assign('key_name', get_platform_check_data($this->__seller_info['id']));
        $this->display();
    }

    /**
     * 平台添加
     */
    public function platformBindAdd() {
        if (IS_POST) {
            $model = D('CustomerPlatformBind');
            $this->__post['poster']['customer_id'] = $this->__seller_info['id'];
            $this->__post['poster']['create_time'] = time();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->__post['poster']['url'] . '/' . get_platform_check_data($this->__seller_info['id']) . '.txt');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if ($httpCode != 200) {
                $this->error('未检测到平台的验证文件，请核对！');
            }

            //检测标识是否存在
            if ($model->where(array('identification' => $this->__post['poster']['identification'], 'customer_id' => $this->__seller_info['id']))->find()) {
                $this->error('平台标示已存在，请更换');
            }

            if ($model->create($this->__post['poster']) === false) {
                $this->error($model->getError());
            }
            if ($model->add() === false) {
                $this->error('信息录入失败，请重新录入');
            }
            $this->success('数据录入成功', U('Accunt/platformBind'));
        } else {
            $this->display();
        }
    }

    /**
     * 平台修改
     */
    public function platformBindSave() {
        if (IS_POST) {
            $model = D('CustomerPlatformBind');
            //检测标识是否存在
            if ($model->where(array('identification' => $this->__post['poster']['identification'], 'id' => array('neq', $this->__post['poster']['id']), 'customer_id' => $this->__seller_info['id']))->find()) {
                $this->error('平台标示已存在，请更换');
            }
            if ($model->create($this->__post['poster']) === false) {
                $this->error($model->getError());
            }
            if ($model->save() === false) {
                $this->error('信息修改失败，请重新录入');
            }
            $this->success('数据修改成功', U('Accunt/platformBind'));
        } else {
            if (isset($this->__get['id']) && intval($this->__get['id']) > 0) {
                $this->assign('info', M('customer_platform_bind')->where(array('customer_id' => $this->__seller_info['id'], 'id' => $this->__get['id']))->find());
                $this->display();
                exit;
            }
            $this->error('参数错误！');
        }
    }

    /**
     * 平台状态修改
     */
    public function platformBindStatusSave() {
        if (isset($this->__get['id']) && intval($this->__get['id']) > 0) {
            if (M('customer_platform_bind')->where(array('customer_id' => $this->__seller_info['id'], 'id' => $this->__get['id']))->save(array('status' => $this->__get['status']))) {
                $this->success('状态修改成功');
            } else {
                $this->error('删除失败！');
            }
        }
        $this->error('参数错误！');
    }

    /**
     * 平台删除
     */
    public function platformBindDel() {
        if (isset($this->__get['id']) && intval($this->__get['id']) > 0) {
            if (M('customer_platform_bind')->where(array('customer_id' => $this->__seller_info['id'], 'id' => $this->__get['id']))->delete()) {
                $this->success('平台删除成功');
            } else {
                $this->error('删除失败！');
            }
        }
        $this->error('参数错误！');
    }

    /**
     * 验证文件下载
     */
    public function platformCheckKey() {
        $key_name = get_platform_check_data($this->__seller_info['id']);
        $path = SITE_FILE . '/Files/' . $key_name . '.txt';
        file_put_contents($path, '1');
        $fileinfo = pathinfo($path);
        header('Content-type: application/x-' . $fileinfo['extension']);
        header('Content-Disposition: attachment; filename=' . $fileinfo['basename']);
        header('Content-Length: ' . filesize($filename));
        unlink($path);
        readfile($thefile);
        exit();
    }

    /**
     * 平台通信检测
     */
    public function platformTesting() {
        if (isset($this->__get['id']) && intval($this->__get['id']) > 0) {
            if ($platform_info = M('customer_platform_bind')->where(array('customer_id' => $this->__seller_info['id'], 'id' => $this->__get['id']))->find()) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $platform_info['url'] . '/' . get_platform_check_data($this->__seller_info['id']) . '.txt');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                if ($httpCode == 200) {
                    $this->success('成功');
                } else {
                    $this->error('失败');
                }
                exit;
            } else {
                $this->error('信息错误！');
            }
        }
        $this->error('参数错误！');
    }

    public function apiBand() {
        $model = D('CustomerPlatformBind');
        $info = $model->where(array('customer_id' => $this->__seller_info['id'], 'id' => $this->__get['id']))->find();
        if (IS_POST) {

            if ($this->__post['poster']['loserOrder']) {
                if ($this->apiSend($info['url'] . $this->__post['poster']['loserOrder']) != 200) {
                    $this->error('失败订单同步接口请求失败 请重新填写！');
                }
            }
            if ($this->__post['poster']['sendOrder']) {
                if ($this->apiSend($info['url'] . $this->__post['poster']['sendOrder']) != 200) {
                    $this->error('发货订单同步接口请求失败 请重新填写！');
                }
            }
            unset($this->__post['poster']['id']);
            $order_api = serialize($this->__post['poster']);
            $model->where(array('customer_id' => $this->__seller_info['id'], 'id' => $this->__get['id']))->save(array('order_api' => $order_api));

            $this->success('成功');
        } else {
            $info['order_api'] = unserialize($info['order_api']);
            $this->assign('info', $info);
            $this->display();
        }
    }

    public function apiSend($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode != 200) {
            return FALSE;
        }
        return 200;
    }

    /**
     *   增加收货地址       
     */
    public function address() {
        $data = I('post.');

        $data['customer_id'] = $this->__seller_info['id'];
        $data['add_time'] = time();
        $id = M('address')->add($data);
        $msg['error'] = 0;
        if ($id) {
            $msg['error'] = 1;
            $msg['address_id'] = $id;
        }

        $this->ajaxReturn($msg);
    }
    
    
    /**
     * 本地账户
     */
    public function local() {
        $account = M('customer')->find( $this->__seller_info['id'] );
        $this->assign( 'account' , $account );
        $lists = M('customer_money_log')->where(array('customer_id' => $this->__seller_info['id']))->page( $this->__page , $this->__row)->order( 'id DESC' )->select();
        $total = M('customer_money_log')->where(array('customer_id' => $this->__seller_info['id']))->count();
        $this->assign('lists' , $lists);
        $this->__assignPage($total);
        $this->display();
    }
    
    /**
     * 预存款充值
     */
    public function localRecharge() {
        $this->assign('alipay_id' , M('payment_config')->where( array( 'default' => 1 , 'type' => 1 ) )->getField('id'));
        $this->assign('weixin_id' , M('payment_config')->where( array( 'default' => 1 , 'type' => 2 ) )->getField('id'));
        $this->display();
    }
    
    
     /**
     * 
     * 图片上传公共方法
     */
    public function uploadFile(){
        $typeArr = array("jpg", "png", "gif");//允许上传文件格式 
        if (isset($_POST)) { 
            $name = $_FILES['file']['name']; 
            $size = $_FILES['file']['size']; 
            $name_tmp = $_FILES['file']['tmp_name']; 
            if (empty($name)) { 
                echo json_encode(array("error"=>"您还未选择图片")); 
                exit; 
            } 
            $type = strtolower(substr(strrchr($name, '.'), 1)); //获取文件类型 

            if (!in_array($type, $typeArr)) { 
                echo json_encode(array("error"=>"清上传jpg,png或gif类型的图片！")); 
                exit; 
            } 
            if ($size > (500 * 1024)) { 
                echo json_encode(array("error"=>"图片大小已超过500KB！")); 
                exit; 
            } 
            
            $pic_name = time() . rand(10000, 99999) . "." . $type;//图片名称 
                //上传路径
            $path = "/Uploads/".date('Y-m-d',time()).'/';
            $file_path = SITE_FILE.$path;
            if( !file_exists( $file_path ) ) {
                    mkdir( $file_path , 0777 , true );
            }
            $pic_url = $file_path . $pic_name;//上传后图片路径+名称 
            if (move_uploaded_file($name_tmp, $pic_url)) { //临时文件转移到目标文件夹 
                exit(json_encode(array("error"=>"0","pic"=>$path.$pic_name,"name"=>$pic_name))); 
            } else { 
                exit(json_encode(array("error"=>"上传有误，清检查服务器配置！"))); 
            } 
    }
    }
    
    public function takeMoney() {
        $this->assign('account_list' , M('customer_take_account')->where(array('customer_id' => $this->__seller_info['id']))->select());
        $this->assign('local' , M('customer')->where(array('id' => $this->__seller_info['id']))->getField('money'));
        $this->display();
    }
    
    public function payAccuntAdd() {
        if( IS_POST ) {
            $data = I('post.poster');
            if( !$data ) $this->error('没有添加的数据');
            $data['customer_id'] = $this->__seller_info['id'];
            $data['create_time'] = time();
            if( M('customer_take_account')->create( $data ) === false ) {
                $this->error('数据添加出错');
            }
            $inser_id = M('customer_take_account')->add( );
            if( $inser_id === false ) {
                $this->error('数据添加出错');
            }
            $data['id'] = $inser_id;
            tipsDivError('信息添加成功' ,'success', 'var data_json = '. json_encode($data) . ';parent.takeAccuntAdd(data_json);');
        }
        $this->display();
    }
    
    public function payAccuntSave() {
        if( IS_POST ) {
            $data = I('post.poster');
            if( !$data ) $this->error('没有修改的数据');
            $data['customer_id'] = $this->__seller_info['id'];
            if( M('customer_take_account')->create( $data ) === false ) {
                $this->error('数据修改出错');
            }
            if( M('customer_take_account')->save( ) === false ) {
                $this->error('数据修改出错');
            }
            $data = M('customer_take_account')->find( $data['id'] );
            tipsDivError('信息修改成功' ,'success', 'var data_json = '. json_encode($data) . ';parent.takeAccuntSave(data_json);');
        }
        $make_accunt = M('customer_take_account')->where(array('customer_id' => $this->__seller_info['id'],'id' => $this->__get['id']))->find();
        if( !$make_accunt ) {
            tipsDivError('您要修改的信息不存在');
        }
        $this->assign('data' , $make_accunt );
        $this->display('payAccuntAdd');
    }
    
    public function payAccuntDelete() {
        if( isset( $this->__get['id'] ) && intval($this->__get['id']) > 0 ) {
            if( M('customer_take_account')->where(array('customer_id' => $this->__seller_info['id'] , 'id' => $this->__get['id']))->delete() ) {
                $this->success("删除成功");
            } else {
                $this->success("删除失败");
            }
        }
    }
    
    public function customerWithdrawals() {
        $account_id = isset( $this->__post['account_id'] ) && intval($this->__post['account_id']) > 0 ? $this->__post['account_id'] : $this->error('错误');
        $note = isset( $this->__post['note'] ) && $this->__post['note'] ? $this->__post['note'] : "";
        $money = isset( $this->__post['money'] ) && intval($this->__post['money']) > 0 ? intval($this->__post['money']): $this->error('信息错误');
        
        $customer_info = M('customer')->find( $this->__seller_info['id'] );
        if( $money > $customer_info['money'] ) {
            $this->error('提现金额不能大于本地账户金额');
        }
        
        $data = array(
            "customer_id" => $this->__seller_info['id'],
            'money' => $money,
            'account_id' => $account_id,
            'create_time' => time(),
            'note' => $note
        );
        $model = M('customer_withdrawals');
        $model->startTrans();
        if( $model->create( $data ) === false ) {
            $this->error('数据添加失败');
        }
        if( $model->add() === false ) {
            $this->error('申请失败，请重新申请');
        }
        
        if( !M('customer')->save(array('id' => $this->__seller_info['id'],'money' => $customer_info['money'] - $money,'frozen_money' => $customer_info['frozen_money'] + $money))) {
            $model->rollback();
            $this->error('申请失败，请重新申请');
        }
        $model->commit();
        D('CustomerMoneyLog')->add(
                array('customer_id' => $this->__seller_info['id'], 'money' => $money, 'type' => 2, 'content' => "申请提现【{$money}】元", 'create_time' => time())
        );
        $this->success("提现申请成功");
    }
    
    public function takeMoneyList() {
        $lists = M('customer_withdrawals')->alias('cw')->where(array('cw.customer_id' => $this->__seller_info['id']))->join('__CUSTOMER_TAKE_ACCOUNT__ cta ON cta.id = cw.account_id')
                                          ->field('cw.*,cta.account_no,cta.account_name')
                                          ->page( $this->__page , $this->__row)->order( 'cw.id DESC' )->select();
        $total = M('customer_withdrawals')->where(array('customer_id' => $this->__seller_info['id']))->count();
        $this->assign('lists' , $lists);
        $this->__assignPage($total);
        $this->display();
    }
    
    public function takeMoneyDelete() {
        $make_id = isset( $this->__get['id'] ) && intval($this->__get['id']) > 0 ? $this->__get['id'] : $this->error('错误');
        if( M('customer_withdrawals')->where(array('id' => $make_id, 'customer_id' => $this->__seller_info['id'] , 'status' => 1))->delete() ) {
            $this->success('信息移除成功');
        } else {
            $this->error('失败');
        }
    }
}
